package xiaopiya.robot.handler.joke;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

/**
 * @author Ray (ayufox@gmail.com)
 * @version 0.1
 */
public class JdbcJokeService extends JdbcDaoSupport implements IJokeService
{
	private final static Log LOG = LogFactory.getLog(JdbcJokeService.class);

	public String getJoke(int type)
	{
		if (LOG.isInfoEnabled())
		{
			LOG.info("extract joke for type[" + type + "]");
		}
		ResultSetExtractor resultSetExtractor = new ResultSetExtractor()
		{
			public Object extractData(ResultSet rs)
					throws SQLException, DataAccessException
			{
				if (rs.next())
				{
					return rs.getString(1);
				} else
				{
					return "没有可用的笑话";
				}
			}
		};
		if (type == 0)
		{
			String sql = "select joke from xiaopiya_jokes order by dbms_random.value()";
			return (String) getJdbcTemplate().query(sql,
					resultSetExtractor);
		} else
		{
			String sql = "select joke from xiaopiya_jokes where joketype = ? order by dbms_random.value()";
			return (String) getJdbcTemplate().query(sql, new Object[]
			{ type }, resultSetExtractor);
		}
	}
}
